package com.ruoyi.factory.staffSafe.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.common.utils.IdGen;
import com.ruoyi.factory.epros.service.impl.EpDataSyncServiceImpl;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import com.ruoyi.factory.staffSafe.domain.StaffsafeInfo;
import com.ruoyi.factory.staffSafe.domain.StaffsafeRecord;
import com.ruoyi.factory.staffSafe.domain.StaffsafeYxtinfo;
import com.ruoyi.factory.staffSafe.mapper.StaffsafeInfoMapper;
import com.ruoyi.factory.staffSafe.mapper.StaffsafeRecordMapper;
import com.ruoyi.factory.staffSafe.mapper.StaffsafeYxtinfoMapper;
import com.ruoyi.factory.staffSafe.service.IYunXuetangService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName YunXuetangServiceImpl
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2024/7/18 08:40
 **/
@Service
public class YunXuetangServiceImpl implements IYunXuetangService {

    protected final Logger logger = LoggerFactory.getLogger(YunXuetangServiceImpl.class);

    @Value("${staffsafe.yunxuetang.url}")
    private String yxtUrl;
    @Value("${staffsafe.yunxuetang.appId}")
    private String yxtAppId;
    @Value("${staffsafe.yunxuetang.appSecret}")
    private String yxtAppSecret;

    @Autowired
    private StaffsafeRecordMapper staffsafeRecordMapper;
    @Autowired
    private StaffsafeInfoMapper staffsafeInfoMapper;
    @Autowired
    private StaffsafeYxtinfoMapper staffsafeYxtinfoMapper;

    public void getyxtstaffinfo(int sl) {
        //先同步之前的信息
        //每天同步一次信息
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //一般是当月 目前为前29个月
        for (int i = 0; i < sl; i++) {
            for (int j = 0; j <2 ; j++) {
                String st="";
                String se="";
                if(j==0){
                    Calendar instance = Calendar.getInstance();
                    instance.add(Calendar.MONTH,-i);
                    instance.set(Calendar.DAY_OF_MONTH,1);
                    Date time = instance.getTime();
                    String format = sdf.format(time);
                    st = format+" 00:00:00";
                    instance.add(Calendar.MONTH,1);
                    instance.add(Calendar.DATE,-15);
                    Date time1 = instance.getTime();
                    String format1 = sdf.format(time1);
                    se = format1+" 23:59:59";
                }else{
                    Calendar instance = Calendar.getInstance();
//                    instance.set(Calendar.DAY_OF_MONTH,1);
                    instance.add(Calendar.MONTH,-i);
                    instance.set(Calendar.DAY_OF_MONTH,1);
                    instance.add(Calendar.MONTH,1);
                    instance.add(Calendar.DATE,-14);
                    Date time = instance.getTime();
                    String format = sdf.format(time);
                    st = format+" 00:00:00";
                    instance.add(Calendar.DATE,13);
                    Date time1 = instance.getTime();
                    String format1 = sdf.format(time1);
                    se = format1+" 23:59:59";
                }
                //递归存入信息
                saveyxtinfo(st,se,0);
            }
        }
    }
    //递归存储信息
    public void saveyxtinfo(String st, String se, long t){
        String gettoken = gettoken();
        //先同步之前的信息
        //每天同步一次信息
        String urlxm = yxtUrl + "/v1/rpt2open/public/user/sync/all";
        //递归
        Map<String, Object> body = new HashMap<>();
        body.put("searchStartTime", st);
        body.put("searchEndTime", se);
        body.put("offset", t);
        body.put("limit", "100");
        JSONObject jsonObject = JSONObject.fromObject(body);
        String s = OkHttpUtils.okHttpPostyxt(urlxm, jsonObject.toString(), gettoken);
        JSONObject jsonObject1 = JSONObject.fromObject(s);
        String subMsg = jsonObject1.optString("subMsg");
        if ("success".equals(subMsg)) {
            //将信息整理存到数据库中
            JSONArray jsonArray = jsonObject1.optJSONArray("data");
            for (Object o : jsonArray) {
                JSONObject jsonObject2 = JSONObject.fromObject(o);
                String id = jsonObject2.optString("id");
                String userId = jsonObject2.optString("userId");
                String username = jsonObject2.optString("username");
                String fullname = jsonObject2.optString("fullname");
                String mobile = jsonObject2.optString("mobile");
                String userNo = jsonObject2.optString("userNo");
                StaffsafeYxtinfo sfy = new StaffsafeYxtinfo();
                sfy.setUserno(userNo);
                sfy.setUsername(username);
                List<StaffsafeYxtinfo> staffsafeYxtinfos = staffsafeYxtinfoMapper.selectStaffsafeYxtinfoList(sfy);
                if(staffsafeYxtinfos.isEmpty()){
                    sfy.setId(id);
                    sfy.setUserid(userId);
                    sfy.setFullname(fullname);
                    sfy.setMobile(mobile);
                    staffsafeYxtinfoMapper.insertStaffsafeYxtinfo(sfy);
                }
            }
            t+=100;
            if(!jsonArray.isEmpty()){
                saveyxtinfo(st,se,t);
            }
        }
    }

    public void getstudyrecord(int sl){
//        staffsafeRecordMapper.deleteStaffsafeRecordAll();
        //1先获取项目数据,遍历数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //控制项目月
        for (int i = 0; i <sl ; i++) {
            for (int j2 = 0; j2 < 2; j2++) {
                String st = "";
                String se = "";
                if (j2 == 0) {
                    Calendar instance = Calendar.getInstance();
                    instance.add(Calendar.MONTH, -i);
                    instance.set(Calendar.DAY_OF_MONTH, 1);
                    Date time = instance.getTime();
                    String format = sdf.format(time);
                    st = format + " 00:00:00";
                    instance.add(Calendar.MONTH, 1);
                    instance.add(Calendar.DATE, -15);
                    Date time1 = instance.getTime();
                    String format1 = sdf.format(time1);
                    se = format1 + " 23:59:59";
                } else {
                    Calendar instance = Calendar.getInstance();
//                    instance.set(Calendar.DAY_OF_MONTH,1);
                    instance.add(Calendar.MONTH, -i);
                    instance.set(Calendar.DAY_OF_MONTH, 1);
                    instance.add(Calendar.MONTH, 1);
                    instance.add(Calendar.DATE, -14);
                    Date time = instance.getTime();
                    String format = sdf.format(time);
                    st = format + " 00:00:00";
                    instance.add(Calendar.DATE, 13);
                    Date time1 = instance.getTime();
                    String format1 = sdf.format(time1);
                    se = format1 + " 23:59:59";
                }
                getstuxm(st,se,0,sl);
        }
        }
        logger.info("云学堂培训记录定时任务更新完成----------");
    }

    public void getstuxm(String st,String se,long ts,int sl){
        String gettoken = gettoken();
        String urlxm = yxtUrl+"/v1/rpt2open/public/o2o/project/sync/all";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> body = new HashMap<>();
        body.put("searchStartTime", st);
        body.put("searchEndTime", se);
        body.put("offset", ts);
        body.put("limit", "1000");
        JSONObject jsonObject = JSONObject.fromObject(body);
        String s = OkHttpUtils.okHttpPostyxt(urlxm, jsonObject.toString(), gettoken);
        JSONObject jsonObject1 = JSONObject.fromObject(s);
        String subMsg = jsonObject1.optString("subMsg");
        if ("success".equals(subMsg)) {
            JSONArray jsonArray = jsonObject1.optJSONArray("data");
            for (Object o : jsonArray) {
                JSONObject jsonObject2 = JSONObject.fromObject(o);
                //项目名称
                String projectName = jsonObject2.optString("projectName");
                //项目id
                String projectId = jsonObject2.optString("projectId");
                //培训时间
//                String startTime = jsonObject2.optString("startTime");
//                String startTime = jsonObject2.optString("startTime");
                String createTime = jsonObject2.optString("createTime");
                //创建人
                String principals = jsonObject2.optString("principals");
                //是否删除 0：未删除 1：已删除
                String projectDeleted = jsonObject2.optString("projectDeleted");
                if ("1".equals(projectDeleted)) continue;
                String[] split = principals.split("\\(");
                String cjr = split[0];
                if(!cjr.equals("王凌云")) continue;
                //控制结果月 一般只获取当月,只有开始获取所有月
                for (int j = 0; j < sl; j++) {
                    for (int j23 = 0; j23 < 2; j23++) {
                        String jst = "";
                        String jse = "";
                        if (j23 == 0) {
                            Calendar instance = Calendar.getInstance();
                            instance.add(Calendar.MONTH, -j);
                            instance.set(Calendar.DAY_OF_MONTH, 1);
                            Date time = instance.getTime();
                            String format = sdf.format(time);
                            jst = format + " 00:00:00";
                            instance.add(Calendar.MONTH, 1);
                            instance.add(Calendar.DATE, -15);
                            Date time1 = instance.getTime();
                            String format1 = sdf.format(time1);
                            jse = format1 + " 23:59:59";
                        } else {
                            Calendar instance = Calendar.getInstance();
//                    instance.set(Calendar.DAY_OF_MONTH,1);
                            instance.add(Calendar.MONTH, -j);
                            instance.set(Calendar.DAY_OF_MONTH, 1);
                            instance.add(Calendar.MONTH, 1);
                            instance.add(Calendar.DATE, -14);
                            Date time = instance.getTime();
                            String format = sdf.format(time);
                            jst = format + " 00:00:00";
                            instance.add(Calendar.DATE, 13);
                            Date time1 = instance.getTime();
                            String format1 = sdf.format(time1);
                            jse = format1 + " 23:59:59";
                        }
                        getxyresult(jst,jse,projectId,projectName,createTime,cjr,0);
                    }
                }
            }
            if (!jsonArray.isEmpty()){
                ts+=1000;
                getstuxm(st, se, ts, sl);
            }
        }
    }

    public void getxyresult(String jst, String jse,String projectId, String projectName,String createTime,String cjr,long ts){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //根据id获取培训结果
        String gettoken2 = gettoken();
        String urlxmjg = yxtUrl + "/v1/rpt2open/public/o2o/project/student/sync/all";
        Map<String, Object> body2 = new HashMap<>();
        body2.put("searchStartTime", jst);
        body2.put("searchEndTime", jse);
        body2.put("offset", ts);
        body2.put("limit", "1000");
        body2.put("projectId", projectId);
        JSONObject jsonObjectxmjg = JSONObject.fromObject(body2);
        String s2 = OkHttpUtils.okHttpPostyxt(urlxmjg, jsonObjectxmjg.toString(), gettoken2);
        JSONObject jsonObject3 = JSONObject.fromObject(s2);
        String s1 = jsonObject3.optString("subMsg");
        if ("success".equals(s1)) {
            JSONArray jsonArray1 = jsonObject3.optJSONArray("data");
            for (Object o1 : jsonArray1) {
                JSONObject jsonObject4 = JSONObject.fromObject(o1);
                String id = jsonObject4.optString("stuUserId");
                //是否完成 0 不是 1 是
//                String projectCompleted = jsonObject4.optString("projectCompleted");
                //分数
                String projectScore = jsonObject4.optString("projectScore");
                //项目是否合格 0不合格 1合格
//                String passed = jsonObject4.optString("passed");
                String passed = jsonObject4.optString("projectCompleted");
                //任务数量
                String projectTotalTasksNum = jsonObject4.optString("projectTotalTasksNum");
                //获取用户信息
                StaffsafeYxtinfo staffsafeYxtinfo = staffsafeYxtinfoMapper.selectStaffsafeYxtinfoByUserId(id);
                if (null != staffsafeYxtinfo){
                    List<StaffsafeInfo> staffsafeInfoList = staffsafeYxtinfo.getStaffsafeInfoList();
                    if(!staffsafeInfoList.isEmpty()){
                        StaffsafeInfo staffsafeInfo = staffsafeInfoList.get(0);
                        //整理数据
                        StaffsafeRecord res = new StaffsafeRecord();
                        String uuid = IdGen.uuid();
                        res.setUserCode(staffsafeInfo.getUserCode());
                        res.setRecordtitle(projectName);
                        res.setTeacher(cjr);
                        Date parse = null;
                        try {
                            parse = sdf.parse(createTime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        res.setRecordtime(parse);
                        List<StaffsafeRecord> staffsafeRecords = staffsafeRecordMapper.selectStaffsafeRecordList(res);
                        if(staffsafeRecords.isEmpty()){
                            res.setId(uuid);
                            if (null == staffsafeInfo) continue;
                            res.setUserid(staffsafeInfo.getId());
                            res.setDr("0");
                            res.setRecordtype("线上");
                            if("null".equals(projectTotalTasksNum)){
                                res.setClasshour("1");
                            }else{
                                res.setClasshour(projectTotalTasksNum);
                            }
                            res.setScore(new BigDecimal(projectScore));
                            String passre = "0".equals(passed) ? "不合格" : "合格";
                            res.setRecordresult(passre);
                            res.setRecordresfalse("合格");
                            staffsafeRecordMapper.insertStaffsafeRecord(res);
                        }
                    }
                }
            }
            if(!jsonArray1.isEmpty()){
                ts+=1000;
                getxyresult( jst,  jse, projectId,  projectName, createTime, cjr, ts);
            }
        }
    }


    public String gettoken(){
        String appId = "axrvn4iokfl";
        String appSecret = "NjA4MjlmZWM5MzAz";
        Map<String, Object> body = new HashMap<>();
        // 请求接口地址
        String url = yxtUrl+"/token";
        // url拼接所需参数
        String pathUrl = url + "?" + "appId=" + yxtAppId + "&appSecret=" + yxtAppSecret;
        // 以post方式调用第三方接口,获取响应结果
//        String result = HttpClientUtil.doPost(pathUrl, body, null);
        JSONObject jsonObject = JSONObject.fromObject(body);
        String s = OkHttpUtils.okHttpPost(pathUrl, jsonObject.toString());
        JSONObject jsonObject1 = JSONObject.fromObject(s);
        String accessToken = jsonObject1.optString("accessToken");
        return accessToken;
    }
}
